#!/bin/bash

# @brief, ubuntu下tftp服务器安装配置脚本
# @autor, LinusZhao
# @email, cs86zhao@foxmail.com

# 说明:TFTP（Trivial File Transfer Protocol,简单文件传输协议）是TCP/IP协议族中的一个用来在客户机与服务器之间进行简单文件传输的协议，
# 提供不复杂、开销不大的文件传输服务。端口号为69

# 定义一个执行命令函数,加返回状态判断,执行错误直接退出整个脚本
# 用法说明: exec_cmd sudo apt-get install tftp-hpa
exec_cmd() {
    local cmd=$*
    echo $cmd
    $cmd
    local ret=$?
    if [ $ret -eq 0 ];then
        echo "$cmd successfully."
    else
        echo "$cmd fail ret=$ret."
        # return $ret
        exit $ret
    fi
}

# !1 查看系统是否已经安装,没有安装则执行安装
if [ -n "$(which tftp)" ];then
    echo "The TFTP server has been installed on the system."
else
    exec_cmd sudo apt-get install tftp-hpa tftpd-hpa
fi

# !2 配置服务器
while true
do
    read -p "please input a tftp file directory:" directory
    if [ -n $directory ];then
        exec_cmd sudo mkdir $directory
        exec_cmd sudo chmod 0777 $directory
        echo "TFTP transfer file test" > $directory/test.txt
        break 
    else
        continue
    fi
done

conf_file=/etc/default/tftpd-hpa
if [ -f $conf_file ];then
    # sed 命令中使用变量要改用双引号
    echo "/^TFTP_DIRECTORY=/c\TFTP_DIRECTORY=\"${directory}\""> script.sed
    echo "/^TFTP_ADDRESS=/c\TFTP_ADDRESS=\"0.0.0.0:69\"" >> script.sed
    echo "/^TFTP_OPTIONS=/c\TFTP_OPTIONS=\"-l -c -s\"" >> script.sed
    # cat script.sed
    exec_cmd sudo sed -i -f script.sed $conf_file
    exec_cmd sudo rm -rf script.sed
fi

exec_cmd sudo service tftpd-hpa restart
echo "TFTP installation configuration complete"
tftp_status=$(exec_cmd sudo service tftpd-hpa status |grep 'running')
echo $tftp_status

# !3 使用说明
echo "使用说明:保证开发板和Ubuntu主机处于同一网段; 互相ping是通的."